package uri.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import uri.model.MemberVO;
import uri.model.MessageVO;
import uri.model.messenger.AlreadyFriendException;
import uri.model.messenger.ListVO;
import uri.model.messenger.MessengerService;

/**
 * 작성자 : 이상호 2014-06-24
 * 설명 : 메신저 관련 컨트롤러
 */
@Controller
public class MessengerController {
	@Resource(name="messengerServiceImpl")
	private MessengerService messengerService;
	
	private String path="C:\\java-kosta\\goodjob-workspace\\goodjob-ver1\\WebContent\\WEB-INF\\view\\messenger\\fileupload\\"; //upload path
	
	public MessengerController() {
		new File(path).mkdirs();
	}

	/**
	 * 작성자 : 이상호 2014-06-24
	 * 설명 : 친구 검색 페이지로 이동
	 */
	@RequestMapping("messenger/auth_findFriendView.do")
	public ModelAndView findFriendView(){
		return new ModelAndView("find_friend.messenger");
	}
	
	/**
	 * 작성자 : 이상호 2014-06-24
	 * 설명 : 친구 검색 검색 타입과 검색어를 매개변수로 받는다.
	 * 		
	 * 이미 추가한 친구에 대한 익셉션 처리 해야함
	 */
	@RequestMapping("messenger/auth_findFriend.do")
	@ResponseBody
	public Map findFriend(String findType, String findWord, HttpSession session){
		//System.out.println(findType+" "+findWord);
		Map map=new HashMap();
		if(findType.equals("id") && findWord.equals( ((MemberVO)session.getAttribute("loginMember")).getId() )){
			map.put("flag", "selfFind"); // 익셉션 처리?
		}else{
			List<MemberVO> list=messengerService.findFriend(findType, findWord, ((MemberVO)session.getAttribute("loginMember")).getId());
			/*for(int i=0; i<list.size(); i++){
				if(list.get(i).getId().equals(((MemberVO)session.getAttribute("loginMember")).getId())){
					list.remove(i);
				}
			}*/
			map.put("list", list);
		}
		return map;
	}
	
	/**
	 * 작성자 : 이상호 2014-06-24
	 * 설명 : 친구 추가, 로그인 필요 세션이 필요
	 */
	@RequestMapping("messenger/auth_addFriend.do")
	public ModelAndView addFriend(HttpSession session, String friendId){
		MemberVO loginMember=(MemberVO)session.getAttribute("loginMember");
		String loginId=loginMember.getId();
		HashMap map=new HashMap();
		if(loginId.equals(friendId)){
			map.put("flag", "sameId");
		}else{
			try {
				messengerService.addFriend(loginId,friendId);
			} catch (AlreadyFriendException e) {
				map.put("flag", "alreadyFriend");
				e.printStackTrace();
			}
		}
		return new ModelAndView("messenger/addFriend_result","map",map);
	}
	
	/**
	 * 작성자 : 이상호 2014-06-24
	 * 설명 : 친구 리스트
	 */
	@RequestMapping("messenger/auth_friendList.do")
	public ModelAndView friendList(HttpSession session, String friendListPage){
		MemberVO loginMember=(MemberVO)session.getAttribute("loginMember");
		String loginId=loginMember.getId();
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("loginId",loginId);
		map.put("page", friendListPage);
		ListVO<MemberVO> lvo=messengerService.friendList(map);
		//System.out.println(list);
		HashMap rmap=new HashMap();
		if(lvo.getList().size()==0){
			rmap.put("flag", "noFriend");
		}else{
			rmap.put("lvo", lvo);
		}
//		System.out.println(rmap);
		return new ModelAndView("friend_list.messenger","map",rmap);
	}
	
	/**
	 * 작성자 : 이상호 2014-06-25
	 * 친구삭제
	 */
	@RequestMapping("messenger/auth_deleteFriend.do")
	public ModelAndView deleteFriend(String friend, HttpSession session){
//		System.out.println(friends);
		Map checkboxMap=(Map)session.getAttribute("checkbox");
		String[] friendArr=friend.split(",");
		for(int i=0; i<friendArr.length; i++){
			checkboxMap.remove(friendArr[i]);
		}
		session.setAttribute("checkbox", checkboxMap);
		if(friend!=null && !friend.equals("null")){
			MemberVO mvo=(MemberVO)session.getAttribute("loginMember");
			String loginId=mvo.getId();
			messengerService.deleteFriend(loginId,friend);
		}
		return new ModelAndView("redirect:/messenger/auth_friendList.do");
	}
	
	/**
	 * 작성자 : 이상호 2014-06-26
	 * 메신저 팝업
	 */
	@RequestMapping("messenger/auth_messengerPopup.do")
	public ModelAndView messengerPopup(){
		return new ModelAndView("messenger/messenger_popup");
	}
	
	/**
	 * 작성자 : 이상호 2014-06-26
	 * 팝업창에서 쪽지 보내기 View 제공
	 */
	@RequestMapping("messenger/auth_sendMessagePopup.do")
	public ModelAndView sendMessagePopup(HttpSession session, String friendListPage){
		MemberVO loginMember=(MemberVO)session.getAttribute("loginMember");
		String loginId=loginMember.getId();
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("loginId",loginId);
		map.put("page", friendListPage);
		ListVO<MemberVO> lvo;
		if(loginMember.getPoint()==-1){ // 운영자일 경우 친구리스트가 아닌 멤버리스트를 반환
			lvo=messengerService.memberList(map);
		}else{
			lvo=messengerService.friendList(map);
		}
		/*Map checkbox=(Map)session.getAttribute("checkbox");
		if(checkbox==null){
			checkbox=new HashMap();
			session.setAttribute("checkbox", checkbox);
		}*/
		HashMap rmap=new HashMap();
		if(lvo.getList().size()==0){
			rmap.put("flag", "noFriend");
		}else{
			rmap.put("lvo", lvo);
		}
		return new ModelAndView("messenger/send_message_popup","map",rmap);
	}
	
	/**
	 * 작성자 : 이상호 2014-06-26
	 * 팝업창에서 쪽지 보내기
	 */
	@RequestMapping("messenger/auth_sendMessage.do")
	public ModelAndView sendMessage(HttpSession session, MessageVO msgvo){
		String loginId=((MemberVO)session.getAttribute("loginMember")).getId();
		msgvo.setSender(loginId);
		List<MultipartFile> list=msgvo.getFile();
		ArrayList<HashMap<String,String>> nameList=new ArrayList<HashMap<String,String>>();
		for(int i=0; i<list.size(); i++){
			MultipartFile uploadFile=list.get(i);
			if(!uploadFile.getOriginalFilename().equals("")){
				try {
					HashMap<String,String> map=new HashMap<String,String>();
					uploadFile=list.get(i);
					long now=System.currentTimeMillis();
					SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd_HHmmss");
					String nowTime=sdf.format(now);
					map.put("orgfilename", uploadFile.getOriginalFilename());
					map.put("newfilename", loginId+"_"+nowTime+"_"+uploadFile.getOriginalFilename());
//					System.out.println(map);
					uploadFile.transferTo(new File(path+map.get("newfilename")));
					nameList.add(map);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} // if
		} // for
		messengerService.sendMessage(msgvo,nameList);
		session.setAttribute("checkbox", new HashMap());
		return new ModelAndView("messenger/send_message_result");
	}

	/**
	 * 작성자 : 이상호 2014-06-26
	 * 팝업창에서 보낸쪽지함
	 */
	@RequestMapping("messenger/auth_sentMessagePopup.do")
	public ModelAndView sentMessagePopup(HttpSession session,String sentMessagePage){
		String loginId=((MemberVO)session.getAttribute("loginMember")).getId();
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("loginId", loginId);
		map.put("page", sentMessagePage);
		ListVO<MessageVO> lvo=messengerService.sentMessageList(map);
//		System.out.println(lvo);
		return new ModelAndView("messenger/sent_message_popup","lvo",lvo);
	}
	
	/**
	 * 작성자 : 이상호 2014-06-27
	 * 팝업창에서 받은쪽지함
	 */
	@RequestMapping("messenger/auth_receivedMessagePopup.do")
	public ModelAndView receivedMessagePopup(HttpSession session,String receivedMessagePage){
		String loginId=((MemberVO)session.getAttribute("loginMember")).getId();
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("loginId", loginId);
		map.put("page", receivedMessagePage);
		ListVO<MessageVO> lvo=messengerService.receivedMessageList(map);
		return new ModelAndView("messenger/received_message_popup","lvo",lvo);
	}
	
	@RequestMapping("messenger/auth_fileDownload.do")
	public ModelAndView fileDownload(HttpServletRequest request,
			HttpServletResponse response){
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("path", path);
		map.put("orgfilename",request.getParameter("orgfilename"));
		map.put("newfilename",request.getParameter("newfilename"));
		return new ModelAndView("downloadView",map);
	}
	
	@RequestMapping("messenger/auth_checkbox.do")
	@ResponseBody
	public List checkbox(String checked, String unchecked, HttpSession session, String flag){
		String[] checkedArr=checked.split(",");
		String[] uncheckedArr=unchecked.split(",");
		Map checkboxMap=(Map)session.getAttribute("checkbox");
		if(checkboxMap==null){
			checkboxMap=new HashMap();
			session.setAttribute("checkbox", checkboxMap);
		}
		if(!checkedArr[0].equals("")){
			for(int i=0; i<checkedArr.length; i++)
				checkboxMap.put(checkedArr[i], true);
		}
		if(!uncheckedArr[0].equals("")){
			for(int i=0; i<uncheckedArr.length; i++)
				checkboxMap.put(uncheckedArr[i], false);
		}
		session.setAttribute("checkbox", checkboxMap);
		Iterator<String> it=checkboxMap.keySet().iterator();
		ArrayList<String> list=new ArrayList<String>();
		while(it.hasNext()){
			String key=it.next();
			boolean b=(boolean) checkboxMap.get(key);
			if(b){
				list.add(key);
			}
		}
		System.out.println("check 된 친구 : "+list);
		return list;
	}
	
	@RequestMapping("messenger/getChatting.do")
	@ResponseBody
	public List<Map<String,String>> getChatting(){
		List<Map<String,String>> list=messengerService.getChatting();
		return list;
	}
	
	@RequestMapping("messenger/auth_sendChattingMessage.do")
	@ResponseBody
	public List<Map<String,String>> sendChattingMessage(String chattingMessage, HttpSession session){
		MemberVO mvo=(MemberVO)session.getAttribute("loginMember");
		messengerService.sendChattingMessage(mvo.getId(), chattingMessage);
		return getChatting();
	}
	
	@RequestMapping("messenger/auth_deleteChattingTable.do")
	public ModelAndView deleteChattingTable(HttpSession session){
		MemberVO mvo=(MemberVO)session.getAttribute("loginMember");
		if(mvo.getPoint()==-1){
			messengerService.deleteChattingTable();
		}
		return new ModelAndView("home");
	}
	
}
